package cn.jiedh.app.meiweidk.baseadapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * @name：RecyclerView通用的Adapter
 * @author：司马林
 * @phone：18423134135
 * @createTime：2017/10/20
 */

public abstract class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_NORMAL = 1;
    private Context mContext;
    private int mLayoutId;
    private List<T> mList;
    private LayoutInflater inflater;
    private View mHeaderView;

    public View getHeaderView() {
        return mHeaderView;
    }

    public void setHeaderView(View mHeaderView) {
        this.mHeaderView = mHeaderView;
    }

    public abstract void convert(BaseViewHolder holder, T t, int position);

    public BaseAdapter(Context context, int layoutId, List<T> list) {
        this.mContext = context;
        this.mLayoutId = layoutId;
        this.mList = list;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getItemViewType(int position) {
        if (mHeaderView == null) {
            return TYPE_NORMAL;
        }
        if (position == 0) {
            return TYPE_HEADER;
        }
        return TYPE_NORMAL;
    }

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mHeaderView != null && viewType == TYPE_HEADER) {
            BaseViewHolder holder = BaseViewHolder.get(mHeaderView);
            return holder;
        }
        BaseViewHolder holder = BaseViewHolder.get(mContext, parent, mLayoutId);
        return holder;
    }

    @Override
    public void onBindViewHolder(BaseViewHolder holder, int position) {
        if (getItemViewType(position) == TYPE_HEADER) {
            return;
        }
        if (mHeaderView != null) {
            convert(holder, mList.get(position - 1), position);
        } else {
            convert(holder, mList.get(position), position);
        }
    }

    @Override
    public int getItemCount() {
        if (mHeaderView == null) {
            return mList.size();
        } else {
            return mList.size() + 1;
        }
    }
}